package dkbta.server.util.query;

import java.io.ByteArrayInputStream;
import java.util.Hashtable;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Element;



import dkbta.server.util.exceptions.IllegalQueryException;
import dkbta.util.Pair;
import static dkbta.util.Utils.now;

import java.text.SimpleDateFormat;
import java.util.Calendar;


/**
 * @author Arkady Mishiev
 *
 */

public class Query {

	private static int s_coundId = 1;
	private final String m_id;
	private final String m_xml;
	private Hashtable<String, PlanPair> m_plansMap;/*<stubId,<plan,result>>*/
	private final String m_clientId;
	private int m_resultsCount;
	private String m_failureReason;
	private static int s_aggregate = 0;
        private PlanState m_state;
	private final String m_startTime;
        private String m_finishTime;

	public Query(String xml, String clientId){
		m_resultsCount = 0;
		m_xml = xml;
		m_id = Integer.toString(s_coundId++);
		m_clientId = clientId;                
                m_startTime = now("H:mm:ss.SSS");
                m_finishTime = "N/A";
                setState(Query.PlanState.ACCEPTED);
	}

        public synchronized void setState(PlanState state){
            m_state = state;
        }

        public PlanState getState(){
            return m_state;
        }

    public String getStartTime() {
        return m_startTime;
    }

    public String getFinishTime() {
        return m_finishTime;
    }

    public void setFinishTime() {
        m_finishTime = now("H:mm:ss.SSS");
    }

      	public enum PlanState{
            ACCEPTED, 
            ANALYZING,
            DISPATCHING,
            PROCESSING,
            AGGREGATING,
            RETURNED
	}

	
	public String getId(){
		return m_id;
	}

	public String getXMLString() {	
		return m_xml;
	}

	/*<stubId,<plan,result>>*/
	public Hashtable<String, PlanPair> getPlans(){
		return m_plansMap;
	}
	
	public void setPlans(Hashtable<String, PlanPair> plansMap) {
		m_plansMap = plansMap;
	}

//	public void setClientId(String cId) {
//		m_clientId = cId;		
//	}

	public synchronized Results addResults(String results, String stubId) {
		Results res = null;
		PlanPair plan = m_plansMap.get(stubId);
		plan.setResult(results);
		m_resultsCount++;
		if(m_resultsCount == m_plansMap.size()){
			String aggregatedResults = aggregateResults();
			res = new Results(m_id,aggregatedResults,m_clientId);
		}
		return res;
	}

	private String aggregateResults() {
		return "-aggregated results #" + (++s_aggregate) + ".";
	}

	public void setFailureReason(String string) {
		m_failureReason = string;		
	}

	public String getClientId() {
		return m_clientId;
	}
}
